package com.emin.platform.subjectcenter.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Map;


/**
 * @author Anson
 * @date 17-3-14
 * @name 参数请求日志输出
 * @since 1.0.1
 */
public class RequestLoggerInterceptor extends HandlerInterceptorAdapter {

    private static final Logger LOGGER = LoggerFactory.getLogger(RequestLoggerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object
            handler) throws Exception {
        response.addCookie(new Cookie("JSESSIONID", request.getSession().getId()));
        // log追加： sessionID - IP - URL - 请求参数
        StringBuffer log = new StringBuffer();
        log.append(" - ").append(request.getSession().getId());
        log.append(" - ").append(request.getRemoteAddr());
        log.append(" - ").append(request.getServletPath());
        if (request.getQueryString() != null) {
            log.append(" - ").append(request.getQueryString()).append(" - ");
        } else {
            Map<String, String[]> parameters = request.getParameterMap();
            if (parameters.size() != 0) {
                log.append(" - [");
            }
            for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                String message = "";
                if (value.getClass().isArray()) {
                    Object[] args = (Object[]) value;
                    message = " " + key + "=" + Arrays.toString(args) + " ";
                } else {
                    message = key + "=" + (String) value + " ";
                }
                log.append(message);
            }
            if (parameters.size() != 0) {
                log.append("]");
            }
        }
        LOGGER.info(log.toString());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object
            handler, ModelAndView modelAndView) throws Exception {


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object
            handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse
            response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
    }

}
